package com.dictionary.hi;

import org.json.JSONArray;
import org.json.JSONObject;

import com.custom.tab.AbstractTabRootManager;
import com.custom.tab.AbstractViewController;
import com.inapp.util.BillingService;
import com.mango9x.utils.HttpHelpers;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.BitmapDisplayer;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewAnimator;

@SuppressLint("HandlerLeak")
public class ShowCategoryViewController extends AbstractViewController {

	public static final String KEY_CATEGORY_URL = "KEY_CATEGORY_URL";
	public static final String KEY_CATEGORY_DATA = "KEY_CATEGORY_DATA";
	public static final String KEY_LOAD_TYPE = "KEY_LOAD_TYPE";
	public static final int LOAD_TYPE_URL = 1;
	public static final int LOAD_TYPE_DATA = 2;

	private MainTabHostActivity mainTabHostActivity;
	private String[] imageUrlsSmall;
	private DisplayImageOptions options;
	private String[] imageUrlsBig;
	private String[] imageIds;
	private String[] likes;
	private String[] dislikes;
	private View v;
	private GridView gridView;
	private ViewAnimator mainViewAnimator;
	private TextView messageView;
	private ImageAdapter imageAdapter;
	private int gridImageWidth;
	private int gridImageHeight;
	private Bundle bundle;

	public ShowCategoryViewController(AbstractTabRootManager tabRootManager,
			Bundle args) {
		super(tabRootManager, R.layout.vc_image_grid);
		try {
			mainTabHostActivity = (MainTabHostActivity) getActivity();
			bundle = args;

			gridImageWidth = (int) Math.ceil(mainTabHostActivity
					.getDisplyWidth() / 3.0);
			gridImageHeight = (65 * gridImageWidth) / 100;

			v = getView();
			mainViewAnimator = (ViewAnimator) v
					.findViewById(R.id.main_view_flipper);
			gridView = (GridView) v.findViewById(R.id.gridview);
			messageView = (TextView) v
					.findViewById(R.id.progress_message_text_view);
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.loading)
					.showImageForEmptyUri(R.drawable.ic_launcher)
					.displayer(new BitmapDisplayer() {

						public Bitmap display(Bitmap bitmap, ImageView imageView) {
							imageView.setAnimation(AnimationUtils
									.loadAnimation(mainTabHostActivity,
											R.anim.fade_in));
							imageView.setImageBitmap(bitmap);
							return bitmap;
						}
					}).cacheInMemory().cacheOnDisc().build();

			downloadandShowData();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void loadData() {

		try {
			
//			boolean isProVersion = BillingService.isPurchased(
//					getSharedPreferences(), Extra.IN_APP_PRODUCT_ID)
//					|| mainTabHostActivity.getPackageName().endsWith("pro");
	
			JSONObject json = null;
			if (bundle.getInt(KEY_LOAD_TYPE, LOAD_TYPE_URL) == LOAD_TYPE_URL) {			
				json = HttpHelpers.getJSONfromURL(bundle
						.getString(KEY_CATEGORY_URL));
			} else {
				json = new JSONObject(bundle.getString(KEY_CATEGORY_DATA));
			}

			JSONArray items = json.getJSONArray("images");
			imageIds = new String[items.length()];
			imageUrlsSmall = new String[items.length()];
			imageUrlsBig = new String[items.length()];
			likes = new String[items.length()];
			dislikes = new String[items.length()];

			for (int i = 0; i < items.length(); i++) {
				JSONArray e = items.getJSONArray(i);
				imageIds[i] = e.getString(0);
				imageUrlsBig[i] = e.getString(1);
				imageUrlsSmall[i] = e.getString(2);
				likes[i] = e.getString(3);
				dislikes[i] = e.getString(4);

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void downloadandShowData() {
		new AsyncTask<String, String, String>() {
			protected void onPreExecute() {
				try {
					messageView.setText(R.string.loading);
					mainViewAnimator.setDisplayedChild(0);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			protected String doInBackground(String... arg0) {
				try {
					loadData();

				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(String unused) {
				try {

					imageAdapter = new ImageAdapter(getActivity());
					gridView.setAdapter(imageAdapter);
					gridView.setOnItemClickListener(new OnItemClickListener() {
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							startImageGalleryActivity(position);
						}
					});
					mainViewAnimator.setDisplayedChild(1);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute();
	}

	public void onDestroy() {
		try {
			mainTabHostActivity.getImageLoader().stop();
			if ((!mainTabHostActivity.isProVersion())
					&& (bundle.getInt(KEY_LOAD_TYPE, LOAD_TYPE_URL) == LOAD_TYPE_URL)) {
				int count = getSharedPreferences().getInt(
						Extra.CATEGORY_SHOW_COUNT, 0) + 1;
				getSharedPreferences().edit()
						.putInt(Extra.CATEGORY_SHOW_COUNT, count).commit();
				if (count % 50 == 0) {

					boolean isProVersion = BillingService.isPurchased(
							getSharedPreferences(), Extra.IN_APP_PRODUCT_ID)
							|| mainTabHostActivity.getPackageName().endsWith(
									"pro");
					if (!isProVersion) {
						mainTabHostActivity.purchasePopup();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	private void startImageGalleryActivity(int position) {
		Bundle bundle = new Bundle();
		bundle.putStringArray(Extra.IMAGE_IDS, imageIds);
		bundle.putStringArray(Extra.IMAGES, imageUrlsBig);
		bundle.putStringArray(Extra.LIKES, likes);
		bundle.putStringArray(Extra.DISLIKES, dislikes);
		bundle.putInt(Extra.IMAGE_POSITION, position);
		pushViewController(new ImagePagerViewController(getTabRootManager(),
				bundle));
	}

	public class ImageAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public ImageAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return imageUrlsSmall.length;
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.item_grid_view, null);
				holder = new ViewHolder();
				holder.imageView = (ImageView) convertView
						.findViewById(R.id.image);
				holder.imageView.getLayoutParams().width = gridImageWidth;
				holder.imageView.getLayoutParams().height = gridImageHeight;

				convertView.setTag(holder);

			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			mainTabHostActivity.getImageLoader().displayImage(
					imageUrlsSmall[position], holder.imageView, options);

			// mainTabHostActivity.getImageLoader().displayImage(
			// imageUrlsSmall[position], holder.imageView, options,
			// new SimpleImageLoadingListener() {
			// public void onLoadingComplete() {
			// Animation anim = AnimationUtils.loadAnimation(
			// mainTabHostActivity, R.anim.fade_in);
			// holder.imageView.setAnimation(anim);
			// anim.start();
			// }
			// });
			return convertView;
		}

		class ViewHolder {
			ImageView imageView;
		}
	}
}